const state = {
  // 商品列表
  productList: [
    {
      id: 1,
      name: '前端',
      price: 5000
    },
    {
      id: 2,
      name: '后端',
      price: 8000
    },
    {
      id: 3,
      name: '测试',
      price: 4000
    },
    {
      id: 4,
      name: '运维',
      price: 3500
    }
  ],
  // 购物车列表
  shopList: [
    {
      id: 2,
      num: 4
    }
  ]
}
const getters = {
  // 商品列表
  productList: (state) => state.productList,
  // 购物车列表
  shopList: (state) => {
    return state.shopList.map(({ id, num }) => {
      let pro = state.productList.find((n) => n.id === id)
      return {
        ...pro,
        num
      }
    })
  },
  // 总价格
  sumPrice: (state, getters) => {
    let total = 0
    getters.shopList.forEach((n) => {
      total += n.price * n.num
    })
    return total
  },
  // 总数量
  totalNum: (state, getters) => {
    let total = 0
    getters.shopList.forEach((n) => {
      total += n.num
    })
    return total
  }
}

const mutations = {
  add: (state, { id }) => {
    let pro = state.shopList.find((item) => item.id === id)
    if (!pro) {
      state.shopList.push({
        id,
        num: 1
      })
    } else {
      pro.num++
    }
  },
  del: (state, { id }) => {
    state.shopList = state.shopList.filter((item) => item.id !== id)
  },
  clear: (state) => {
    state.shopList = []
  }
}

const actions = {
  // 添加购物车操作
  addToCart({ commit }, product) {
    commit('add', {
      id: product.id
    })
  },
  // 删除指定商品
  delProduct({ commit }, product) {
    commit('del', {
      id: product.id
    })
  },
  // 清空购物车
  clearAll({ commit }) {
    commit('clear')
  }
}
export default {
  state,
  mutations,
  actions,
  getters
}
